package com.qdu.hyy.DirectorAverageRating;
import com.qdu.hyy.MovieWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;


//job3 end!
public class DirectorAverageRatingMapper extends Mapper<Object, Text, Text, DoubleWritable> {

    private Text director = new Text();
    private DoubleWritable score = new DoubleWritable();

    @Override
    protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {

        String[] fields = value.toString().split(","); // 使用逗号作为分隔符

        if (fields.length >= 22) { // 确保有足够的字段

            director = new Text(fields[21]);
//        score = new DoubleWritable(Double.parseDouble(fields[12]));
//

            String voteAverageStr = (fields[12]); // 从文件或输入流中获取的字符串


            if (voteAverageStr != null && !voteAverageStr.trim().isEmpty()) {
                try {
                    // 尝试将字符串转换为double
                    score = new DoubleWritable(Double.parseDouble(voteAverageStr.trim()));

                    context.write(director, score);
                    // 转换成功，进行后续处理
                } catch (NumberFormatException e) {
                    // 转换失败，处理异常，例如记录日志或跳过当前记录
                    System.err.println("无法将字符串转换为double: " + voteAverageStr);
                }
            } else {
                // 字符串为空，处理空值情况，例如记录日志或跳过当前记录
                System.err.println("voteAverageStr为空");
            }
        }
    }
}